<?php

namespace catchAdmin\externalGoods\service;

use catchAdmin\customs\model\HnOrderDetail;
use catchAdmin\customs\model\OrderSon;
use catchAdmin\externalGoods\model\Category;
use catchAdmin\externalGoods\model\GoodsAttribute;
use catchAdmin\externalGoods\model\GoodsRule;
use think\facade\Request;
use catchAdmin\externalGoods\model\Goods as externalGoodsModel;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\Code;
use houniao\api\v1\Goods;
use think\Exception;
use think\facade\Db;

class RemoteGoodsService{

    protected $user;
    protected $price_fl = 1.1;

    public static $trade_type_option = [
        1 => "保税直供",
        2 => "完税进口",
        3 => "国内贸易",
        4 => "香港直邮",
        5 => "海外直邮",
    ];

    public static $spec_convert = [
        0 => 1,
        1 => 2
    ];

    //海淘汇商品
    public function hthGoodsFieldFormat(&$data){
        $cateModel = new Category;

        $format = [];
        $format['ext_id'] = $data['sys_spu'];
        $format['goods_spu'] = $data['sys_spu'];
        $format['goods_name'] = $data['store_name'];
        $format['goods_subtitle'] = '';
        $format['goods_keywords'] = $data['keyword'];
        $format['goods_img'] = $data['image'];

//        if(!is_array($data['slider_image']) || empty($data['slider_image'])){
//            $data['slider_image'] = [];
//        }
        $format['goods_slideshow_img'] =  json_encode($data['slider_image']);

        $format['barcode'] = $data['bar_code'];//商品编码
        $format['brand_id'] = $data['brand']['brand_id'];
        $format['brand_name'] = $data['brand']['brand_name'];
        $format['sync_brand_id'] = $data['brand']['brand_id'];
        $format['sync_brand_name'] = $data['brand']['brand_name'];
//        $format['origin_id'] = '';
        $format['origin_name'] = $data['area'];
        $format['trade_type_id'] = $data['trade_type'];
        $format['trade_type_name'] = self::$trade_type_option[$data['trade_type']] ;
        $format['unit_name'] = $data['unit_name'];
        $format['unit_id'] = '';

        if(0 ==  $data['is_show']){//不显示
            $format['is_sale'] = 0;//不显示就先下架
        }else{
            $format['is_sale'] = $data['status'];
        }
//        $format['is_sys_api'] = 1;

        $format['sync_category_id'] =  $data['mer_cate_id'][count($data['mer_cate_id']) - 1];  //api传输的cate_id
        $format['category_id'] =  $cateModel->where('hth_cate_id',$format['sync_category_id'])->value('id'); //查询的
        $format['sync_category_id_path'] = implode('_',$data['mer_cate_id']);
        $format['sync_category_name'] = '';
        $format['supplier_id'] = 2;
        $format['spec'] = self::$spec_convert[$data['spec_type']];
        $format['market_price'] = $data['price'];
        $format['description'] = $data['content'];

        return $format;
    }

    //海淘汇属性
    public function hthGoodsAttrFieldFormat(&$data){
        $return = [];
        $data_attr = $data['attr'];

        $index = 0;
        foreach ($data_attr as $key => $attr){
            foreach ($attr['detail'] as $_key => $_attr){
                $_value = [
                    'attribute_id'=>$data['sys_spu'] . '-' . str_pad(++$index,5,'0',STR_PAD_LEFT),
                    'name'=>$attr['value'],
                    'attribute_name'=>$_attr,
                    'goods_id'=> $data['_goods']['id'] ?? '',
                    'goods_spu'=>$data['sys_spu'],
                    'supplier_id'=>2
                ];
                $return[] = $_value;
                $key = $_value['name'] . ":" . $_value['attribute_name'];
                $data['_attr'][$key] = $_value['attribute_id'];
            }
        }

//        dd($return);

        return $return;
    }

    //海淘汇规格
    public function hthGoodsRuleFieldFormat(&$data){
        $return = [];
        $data_rule = $data['attrValue'];

        //dd($data_rule);
        $cost_price_arr = [];
        $market_price_arr = [];
        $sku_price_arr = [];
        $stock = 0;

        foreach ($data_rule as $rule){
            $detail_arr = [];
            $spec_sku = [];
            $attr_value = [];

            //dd($rule['detail']);

            foreach ($rule['detail'] as $k => $d){
                $a_k = $k . ":" . $d;
                $detail_arr[] = $a_k;
                $spec_sku[] = $data['_attr'][$a_k];
                $attr_value[] = $d;
            }

            $spec_sku_str = implode('_',$spec_sku);
            $detail_arr_str = implode(';',$detail_arr);

            //dd($attr_value);

            $ruleData = [
                'ext_id'=>$rule['attr_value_id'],
                'goods_sku'=>$rule['sys_sku'],
                'goods_id'=>$data['_goods']['id'] ?? '',
                'goods_spu'=>$rule['sys_spu'],
                'spec_sku'=>$spec_sku_str,
                'sku_name'=>$detail_arr_str,
                'sku_attribute_id'=> json_encode($spec_sku),
                'sku_attribute_name'=> json_encode($attr_value,JSON_UNESCAPED_UNICODE),
                'cost_price'=> $rule['price'],
                'market_price'=> $rule['price'],
                'sku_price'=> round($rule['price'] * $this->price_fl),
                'sku_weight'=>$rule['weight'],
//                'sku_quantity'=>$rule['']
                'sku_stock'=>$rule['stock'],
                'spec_img'=>$rule['image'],
                'supplier_id'=>2
            ];

            $return[] = $ruleData;

            if($ruleData['cost_price'] > 0){
                $cost_price_arr[] = $ruleData['cost_price'];
                $market_price_arr[] = $ruleData['market_price'];
                $sku_price_arr[] = $ruleData['sku_price'];
                $stock += $ruleData['sku_stock'];
            }
        }

        $data['_rule_info'] = [
            'cost_price'=>min($cost_price_arr),
            'market_price'=>min($market_price_arr),
            'price'=>min($sku_price_arr),
            'stock'=>$stock
        ];

        return $return;
    }

    //海淘汇添加商品
    public function hthGoodsAdd($data){
        Db::startTrans();
        try {
            $formatData =  $this->hthGoodsFieldFormat($data);

            //如果是保税商品，直接跳过
            if(1 == $formatData['trade_type_id']){
                return ['status'=>1];
            }

            $goodsModel = new externalGoodsModel;
            $goodsAttrModel = new GoodsAttribute;
            $goodsRuleModel = new GoodsRule;
            $id =  $goodsModel->storeBy($formatData);

            $data['_goods'] = ['id'=> (int) $id];

            $formatData =  $this->hthGoodsAttrFieldFormat($data);
            $goodsAttrModel->insertAll($formatData);

            $formatData =  $this->hthGoodsRuleFieldFormat($data);
            $goodsRuleModel->insertAll($formatData);

            //更新商品库存和价格
            $goodsModel->updateBy($id,$data['_rule_info']);

            Db::commit();
            return ['status'=>1];
        }catch (\Exception $exception){
            Db::rollback();
            return ['status'=>0,'msg'=>$exception->getMessage()];
        }
    }

    //海淘汇更新商品
    public function hthGoodsUpdate($goods_pk,$goods_spu,$list){
        Db::startTrans();
        try {
            $goodsModel = new externalGoodsModel;
            $goodsAttrModel = new GoodsAttribute;
            $goodsRuleModel = new GoodsRule;
            $remoteGoodsService = new RemoteGoodsService;

            //格式化字段
            $formatData =  $remoteGoodsService->hthGoodsFieldFormat($list);
            $list['_goods'] = ['id'=> (int) $goods_pk];
            //属性
            $attrFormatData =  $remoteGoodsService->hthGoodsAttrFieldFormat($list);
            //规格
            $ruleFormatData =  $remoteGoodsService->hthGoodsRuleFieldFormat($list);

            /**
             * 1 商品更新
             */
            $goodsModel->where(['goods_spu'=>$goods_spu])->save($formatData);

            $attr = $goodsAttrModel->where(['goods_spu'=>$goods_spu])->select()->toArray();
            foreach ($attr as &$_attr){
                $_attr['unique_id'] = "{$_attr['name']}_{$_attr['attribute_name']}";
            }
            $old_attr_ids = array_column($attr,'unique_id');
            $old_goods_attr_combine = array_combine($old_attr_ids,$attr);

            //新的
            foreach ($attrFormatData as &$_attr1){
                $_attr1['unique_id'] = "{$_attr1['name']}_{$_attr1['attribute_name']}";
            }
            $new_attr_ids = array_column($attrFormatData,'unique_id');
            $new_goods_attr_combine = array_combine($new_attr_ids,$attrFormatData);

            //dd($new_attr_ids,$attrFormatData);


            // 查找新增的元素
            $newElements = array_diff($new_attr_ids, $old_attr_ids);
            // 查找需要修改的元素
            $modifyElements = array_intersect($new_attr_ids, $old_attr_ids);
            // 查找需要删除的元素
            $deleteElements = array_diff($old_attr_ids, $new_attr_ids);

            //var_dump($old_goods_attr_combine);die();

            //新增和修改
            foreach ($new_goods_attr_combine as $key => $new_goods_attr){
                $temp = $new_goods_attr;
                unset($temp['unique_id']);
                if(in_array($key,$newElements)){//新增
                    $goodsAttrModel->createBy($temp);
                }
                if(in_array($key,$modifyElements)){//修改
                    $a =  $goodsAttrModel->where(['id'=>$old_goods_attr_combine[$key]['id']])->find();
                    $a->save($temp);
                }
            }
            //删除
            if(!empty($deleteElements)){
                foreach ($deleteElements as $del){
                    $goodsAttrModel->deleteBy([$old_goods_attr_combine[$del]['id']]);
                }
            }


            /**
             * 规格处理
             */
            $rule = $goodsRuleModel->where(['goods_spu'=>$goods_spu])->select()->toArray();

            $old_rule_ids = array_column($rule,'goods_sku');
            $old_goods_rule_combine = array_combine($old_rule_ids,$rule);

            //新的
            $new_rule_ids = array_column($ruleFormatData,'goods_sku');
            $new_goods_rule_combine = array_combine($new_rule_ids,$ruleFormatData);

            //dd($new_attr_ids,$attrFormatData);

            // 查找新增的元素
            $newElements_rule = array_diff($new_rule_ids, $old_rule_ids);
            // 查找需要修改的元素
            $modifyElements_rule = array_intersect($new_rule_ids, $old_rule_ids);
            // 查找需要删除的元素
            $deleteElements_rule = array_diff($old_rule_ids, $new_rule_ids);

            //新增和修改
            foreach ($new_goods_rule_combine as $key => $new_goods_rule){
                if(in_array($key,$newElements_rule)){//新增
                    $goodsRuleModel->createBy($new_goods_rule);
                }
                if(in_array($key,$modifyElements_rule)){//修改
                    $b =  $goodsRuleModel->where(['id'=>$old_goods_rule_combine[$key]['id']])->find();
                    $b->save($new_goods_rule);
                }
            }
            //删除
            if(!empty($deleteElements_rule)){
                foreach ($deleteElements_rule as $del_rule){
                    $goodsRuleModel->deleteBy([$old_goods_rule_combine[$del_rule]['id']]);
                }
            }

            //更新商品库存和价格
            $goodsModel->updateBy($goods_pk,$list['_rule_info']);

            Db::commit();
            return ['status'=>1];
        }catch (\Exception $exception){
            Db::rollback();
            return ['status'=>0,'msg'=>$exception->getMessage()];
        }
    }

    //海淘汇物流单号保存
    public function hthLogisticsFormart($data){
        $return = [];
        $hnOrderDetailModel = new HnOrderDetail;
        $orderSonModel = new OrderSon;

        foreach ($data as $d){
            $hnInfo = $hnOrderDetailModel->where('order_no',$d['order_sn'])->find();
            $supplier_id = $orderSonModel->where('orderlistId',$hnInfo['source_order_no'])->value('goods_supplier_id');
            $_data = [
                'order_id'=> $hnInfo['source_order_no'],
                'main_order_id'=> $hnInfo['main_order_id'],
                'order_no'=> $hnInfo['order_no'],
                'express_no'=> $d['delivery_id'],
                'express_name'=> $d['delivery_name'],
                'express_code'=> '',
                'delivery_time'=> date("Y-m-d H:i:s",time()),
                'supplier_id'=> $supplier_id
            ];

            $return[] = $_data;
        }

        return $return;
    }

    /**
     *      2   下面是巧易云商品
     */

    //qyy商品
    public function qyyGoodsFieldFormat(&$data){
        $cateModel = new Category;

        $format = [];
        $format['ext_id'] = $data['prod'];
        $format['goods_spu'] = $data['prod'];
        $format['goods_name'] = $data['goods_name'];
        $format['goods_subtitle'] = '';
        $format['goods_keywords'] = '';

        $photo = explode(',',$data['photo']);

        $format['goods_img'] = $photo[0];

//        if(!is_array($data['slider_image']) || empty($data['slider_image'])){
//            $data['slider_image'] = [];
//        }
        $format['goods_slideshow_img'] =  json_encode(array_slice($photo,1));

        $format['barcode'] = $data['barcode'];//商品编码
        $format['brand_id'] = 0;
        $format['brand_name'] = $data['bra'];
        $format['sync_brand_id'] = 0;
        $format['sync_brand_name'] = $data['bra'];
//        $format['origin_id'] = '';
        $format['origin_name'] = $data['product_area'];
        $format['trade_type_id'] = $data['trade_type'];
        $format['trade_type_name'] = self::$trade_type_option[$data['trade_type']] ;
        $format['unit_name'] = $data['Unit2'];
        $format['unit_id'] = '';
        $format['is_sale'] = $data['is_show'];
//        $format['is_sys_api'] = 1;

        $format['sync_category_id'] =  '';  //api传输的cate_id
        $format['category_id'] =  ''; //查询的
        $format['sync_category_id_path'] = '';
        $format['sync_category_name'] = '';
        $format['supplier_id'] = 3;
        $format['spec'] = $data['spec_type'];
        $format['market_price'] = $data['price'];
        $format['description'] = $data['detail_img'];

        return $format;
    }

    //qyy商品属性
    public function qyyGoodsAttrFieldFormat(&$data){
        $return = [];
        $data_attr = $data['attr'];

        $index = 0;
        foreach ($data_attr as $key => $attr){

            $cbval = explode('$',$attr['cbval']) ;
            foreach ($cbval as $val){
                $_value = [
                    'attribute_id'=>$data['prod'] . '-' . str_pad(++$index,5,'0',STR_PAD_LEFT),
                    'name'=>$attr['property'],
                    'attribute_name'=>$val,
                    'goods_id'=> $data['_goods']['id'] ?? '',
                    'goods_spu'=>$data['prod'],
                    'supplier_id'=>3
                ];
                $return[] = $_value;
                $key = $_value['name'] . ":" . $_value['attribute_name'];
                $data['_attr'][$key] = $_value['attribute_id'];
            }
        }

//        dd($return);

        return $return;
    }

    //qyy规格
    public function qyyGoodsRuleFieldFormat(&$data){
        $return = [];
        $data_rule = $data['rule'];

        //dd($data_rule);
        $cost_price_arr = [];
        $market_price_arr = [];
        $sku_price_arr = [];
        $stock = 0;

        foreach ($data_rule as $rule){
            $detail_arr = [];
            $spec_sku = [];
            $attr_value = [];

            //dd($rule['detail']);

            $a_k = $rule['pr_name'] . ":" . $rule['suk_val'];
//            $detail_arr[] = $a_k;
//            $spec_sku[] = $data['_attr'][$a_k];
//            $attr_value[] = $d;
//
//
//            $spec_sku_str = implode('_',$spec_sku);
//            $detail_arr_str = implode(';',$detail_arr);

            //dd($attr_value);

            $ruleData = [
                'ext_id'=>$rule['sku_id'],
                'goods_sku'=>$rule['sku_id'],
                'goods_id'=>$data['_goods']['id'],
                'goods_spu'=>$data['prod'],
                'spec_sku'=>$rule['skuNo'],
                'sku_name'=>$a_k,
                'sku_attribute_id'=> json_encode([$rule['skuNo']]),
                'sku_attribute_name'=> json_encode([$rule['suk_val']],JSON_UNESCAPED_UNICODE),
                'cost_price'=> $rule['cost_price'],
                'market_price'=> $rule['translate_price'],
                'sku_price'=> round($rule['cost_price'] * $this->price_fl),
                'sku_weight'=>'',
//                'sku_quantity'=>$rule['']
                'sku_stock'=>$rule['suk_num'],
                'spec_img'=>$rule['photo'],
                'supplier_id'=>3
            ];

            $return[] = $ruleData;

            if($ruleData['cost_price'] > 0){
                $cost_price_arr[] = $ruleData['cost_price'];
                $market_price_arr[] = $ruleData['market_price'];
                $sku_price_arr[] = $ruleData['sku_price'];
                $stock += $ruleData['sku_stock'];
            }
        }

        $data['_rule_info'] = [
            'cost_price'=>min($cost_price_arr),
            'market_price'=>min($market_price_arr),
            'price'=>min($sku_price_arr),
            'stock'=>$stock
        ];

        return $return;
    }

    //qyy添加商品
    public function qyyGoodsAdd($data){

        Db::startTrans();
        try {
            $formatData =  $this->qyyGoodsFieldFormat($data);

            $goodsModel = new externalGoodsModel;
            $goodsAttrModel = new GoodsAttribute;
            $goodsRuleModel = new GoodsRule;
            $id =  $goodsModel->storeBy($formatData);

            $data['_goods'] = ['id'=> (int) $id];

            $formatData =  $this->qyyGoodsAttrFieldFormat($data);
            $goodsAttrModel->insertAll($formatData);
            $formatData =  $this->qyyGoodsRuleFieldFormat($data);
            $goodsRuleModel->insertAll($formatData);

            //更新商品库存和价格
            $goodsModel->updateBy($id,$data['_rule_info']);

            Db::commit();
            return ['status'=>1];
        }catch (\Exception $exception){
            Db::rollback();
            return ['status'=>0,'msg'=>$exception->getMessage()];
        }
    }
}